package com.ilvyou.api.common;

import com.ilvyou.api.bean.result.Result;
import com.ilvyou.api.service.PersonalService;
import com.ilvyou.core.util.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by GuanYuCai on 2016/9/6 0006.
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    private Logger log = Logger.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getParameter("token");
        if (StringUtil.isEmpty(token)){
            needLogin(response);
            log.debug("token " + token + " invalid!");
            return false;
        }else{
            Cache.User user = Cache.get(token);
            if (user == null || !user.isComplete){
                needLogin(response);
                log.debug("token " + token + " invalid!");

                return false;
            }
        }

        return super.preHandle(request, response, handler);
    }

    private void needLogin(HttpServletResponse response) throws IOException {
        Result r = new Result();
        r.setCode(Constant.LOGIN);
        r.setMessage("请登录！");

        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control","no-cache, must-revalidate");
        response.getWriter().write(StringUtil.toJson(r));
    }
}
